﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using XcoAppSpaces.Core;
using Microsoft.Ccr.Core;
using System.Threading;

namespace test.XcoAppSpaces.Core
{
	[TestFixture]
	public class testMessageWithDelegate
	{
		public delegate bool MyBoolFunc<T>(T value);

		[Serializable]
		public class Msg<T>
		{
			public Msg(MyBoolFunc<T> func, T value)
			{
				this.Function = func;
				this.Value = value;
			}

			public MyBoolFunc<T> Function { get; set; }
			public T Value { get; set; }
		}

		public class PBoolFuncWorker : PortSet<Msg<string>, Msg<int>>
		{}

		public class BoolFuncWorker : PBoolFuncWorker
		{
			[XcoConcurrent]
			public void ProcessMsg(Msg<string> msg)
			{
				Console.WriteLine("Msg \"" + msg.Value + "\" received! Func call result: " + msg.Function(msg.Value));
			}

			[XcoConcurrent]
			public void ProcessMsg(Msg<int> msg)
			{
				Console.WriteLine("Msg \"" + msg.Value + "\" received! Func call result: " + msg.Function(msg.Value));
			}
		}

		[Test]
		public void TestFuncMsg()
		{
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8000"),
				space2 = new XcoAppSpace("tcp.port=8001"))
			{
				space1.RunWorker<PBoolFuncWorker, BoolFuncWorker>("worker");
				PBoolFuncWorker worker = space2.ConnectWorker<PBoolFuncWorker>(Environment.MachineName + ":" + 8000 + "/worker");
				worker.Post(new Msg<string>(str => str.Length == 3, "bla"));
				Thread.Sleep(100);
				worker.Post(new Msg<string>(str => str.Length == 3, "bla2"));
				Thread.Sleep(100);
				worker.Post(new Msg<int>(num => num % 2 == 0, 5));
				Thread.Sleep(100);
				worker.Post(new Msg<int>(num => num % 2 == 0, 22));
				Thread.Sleep(1000);
			}
		}
	}
}
